﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TrangTrai.Data.DAO;
using DevExpress.Web.ASPxEditors;
using DevExpress.Web.ASPxClasses;

namespace Trangtrai.tochuc
{
    public partial class UserManage : System.Web.UI.Page
    {
        GroupManagementDAO dao = new GroupManagementDAO();
        static Dictionary<String, UserInfo> currentUserDic = new Dictionary<string, UserInfo>();
        static Dictionary<string, int> roleDic = new Dictionary<string, int>();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                loadData();
                UserInfo[] userList = dao.getAllUsers();
                currentUserDic = userList.ToDictionary(key => key.userCode, value => value);
                dtgUserList.DataSource = userList;
                dtgUserList.DataBind();
            }
            else {
                refreshUserList();
            }
            
        }

        private void loadData(){
            
            cbxStatus.DataSource = dao.getUserStatus(); 
            cbxStatus.DataBind();
            cbxRole.DataSource = dao.getRoles();
            cbxRole.DataBind();
            roleDic = dao.getRoles().ToDictionary(key=>key.roleName, value=> value.roleId);

        }
        public UserInfo getDataFromControls(){
            UserInfo userInfo = new UserInfo();
            userInfo.phone = tbxPhone.Text.Trim();
            userInfo.fullName = tbxName.Text.Trim();
            userInfo.address = tbxAddress.Text.Trim();
            userInfo.userCode = tbxUserCode.Text.Trim();
            userInfo.userStatusId = Int32.Parse(cbxStatus.SelectedItem.Value.ToString());
            userInfo.roleId = Int32.Parse(cbxRole.SelectedItem.Value.ToString());
            return userInfo;
        }
        private int validate() {
            String userCode= tbxUserCode.Text.Trim();
            if (String.IsNullOrEmpty(userCode)) return 1;
            else if (currentUserDic.ContainsKey(userCode))
            { // user code existing
                return 2;
            }
            else {
                return 0;
            }
            
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            int status =validate();
            if (status== 0)
            {
                //save data into database
                dao.addUser(getDataFromControls());
                lblMess.Text = "Thêm mới nhân viên thành công";
                refreshUserList();
            }
            else if (status == 1)
            {

                // display error message
                lblMess.Text = "Bạn chưa nhập mã nhân viên";
            }
            else {
                lblMess.Text = "Mã nhân viên đã tồn tại";
            }
        }

        protected void dtgUserList_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
        {
            UserInfo newUserInfo = new UserInfo();
            newUserInfo.userId = Int32.Parse(e.Keys[0].ToString());
            newUserInfo.fullName = e.NewValues["fullName"].ToString();
            newUserInfo.userCode = e.NewValues["userCode"].ToString();
            newUserInfo.phone = e.NewValues["phone"].ToString();
            newUserInfo.address = e.NewValues["address"].ToString();
            newUserInfo.roleId =e.NewValues["roleName"]==null?roleDic[e.OldValues["roleName"].ToString()]: Int32.Parse(e.NewValues["roleName"].ToString());
            dao.updateUser(newUserInfo);
            refreshUserList();
            e.Cancel = true;

        }
        private void refreshUserList() {
            UserInfo[] userList = dao.getAllUsers();
            currentUserDic = userList.ToDictionary(key => key.userCode, value => value);
            dtgUserList.DataSource = userList;
            dtgUserList.DataBind();
        }

        protected void dtgUserList_CellEditorInitialize(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewEditorEventArgs e)
        {
           
            if(!dtgUserList.IsEditing || e.Column.FieldName != "roleName") return;
           

            ASPxComboBox combo = e.Editor as ASPxComboBox;
            FillCityCombo(combo,"");

            combo.Callback += new CallbackEventHandlerBase(cmbCity_OnCallback);
    
        }
        private void cmbCity_OnCallback(object source, CallbackEventArgsBase e) {
            FillCityCombo(source as ASPxComboBox, e.Parameter);
        }
        
        protected void FillCityCombo(ASPxComboBox cmb, string country) {
           
            //List<string> cities = dao.getRoles();            
            Role[] roles = dao.getRoles();

            cmb.Items.Clear();
            foreach (Role role in roles)
                cmb.Items.Add(role.roleName,role.roleId);
         }

        protected void dtgUserList_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
        {
            int userId = (int)e.Keys[0];
            dao.deleteUser(userId);
            refreshUserList();
            e.Cancel = true;
        }
    }
}
